// AUTHOR: Yiwei (Alan) Han

var g_start;
var g_end;

function ajaxUpdateWorklist(email,start,end){
	if(getCookie('user') != null) {
	initSchedule(start,end);
	getWorklistContent(email);
	getSummary(email);
	getWaypoints(email,'1');
	g_start = start;
	g_end = end;
	}
}

function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("IE5/6 not supported");
	}
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

var worklist_req = getXmlHttpRequestObject();

function getWorklistContent(email) {
	var user = getCookie('user'); 
	if (user != null){
		if (worklist_req.readyState == 4 || worklist_req.readyState == 0) {
			if(email == user)
				worklist_req.open("GET", 'auth/ajax/worklist?action=get', true);
			else
				worklist_req.open("GET", 'auth/ajax/worklist?action=view&email='+email, true);
			worklist_req.onreadystatechange = handleWorklistContent;
			worklist_req.send(null);
		}
	}
}

function handleWorklistContent() {
	if (worklist_req.readyState == 4) {
		var xmlDoc = worklist_req.responseXML;
		if(xmlDoc.getElementsByTagName("response")[0].hasChildNodes()) {
			var parent = xmlDoc.getElementsByTagName("response")[0].getElementsByTagName("item");
				for (k = 0; k < parent.length; k++) {
					var dept = parent[k].getElementsByTagName("dept")[0].childNodes[0].nodeValue;
					var course = parent[k].getElementsByTagName("course")[0].childNodes[0].nodeValue;
					var section = parent[k].getElementsByTagName("section")[0].childNodes[0].nodeValue;
					var start = parent[k].getElementsByTagName("start")[0].childNodes[0].nodeValue;
					var end = parent[k].getElementsByTagName("end")[0].childNodes[0].nodeValue;
					var day = parent[k].getElementsByTagName("day")[0].childNodes[0].nodeValue;
					var building = parent[k].getElementsByTagName("building")[0].childNodes[0].nodeValue;
					var room = parent[k].getElementsByTagName("room")[0].childNodes[0].nodeValue;
					var term = parent[k].getElementsByTagName("term")[0].childNodes[0].nodeValue;
					addSection(start, end, day, dept, course, section, building, room, term);
				}
		}
	}
}

function addSection(start, end, day, dept, course, section, building, room, term){
	if(term == '1-2') {
		addSection(start, end, day, dept, course, section, building, room, '1');
		addSection(start, end, day, dept, course, section, building, room, '2');
		return;
	}
	var schedule = document.getElementById('schedule-'+term);
	var blocksize = ((parseInt(end.split(":")[0]) - parseInt(start.split(":")[0]))*60 + (parseInt(end.split(":")[1]) - parseInt(start.split(":")[1])))/30;
	var timeArray = new Array(blocksize);
	var indicator = 0;
	if((parseInt(start.split(":")[1]) == 30))
		indicator = 1;
	for(i = 0; i < blocksize; i++ ){
		if(i%2 != indicator)
			var time = (parseInt(start.split(":")[0])+parseInt(i/2))+":30";
		else 
			var time = (parseInt(start.split(":")[0])+parseInt((i+1)/2))+":00";
		timeArray[i] = time;
	}
	var dayArray = day.split(" ");
	for(i = 0; i < timeArray.length; i++) {
		for(j = 0; j < dayArray.length; j++) {
			var tdName = dayArray[j]+"-"+timeArray[i]+"-"+term;
			var content = document.getElementById(tdName);
			var html = '<div class="course">';
			var user = getCookie('user');
			if((window.location+"").indexOf(user, (window.location+"").length - user.length) != -1)
				html += '<div class="remove-course" onclick="removeWorklistItem(\''+dept+'\',\''+course+'\',\''+section+'\');" onmouseover="title=\'Delete from worklist\'">&times;</div>';
			//html += '<a target="_blank" href="/detail?type=section&did='+dept+'&cid='+course+'&sid='+section'\">';
			html += '<p class="block-section"  onclick="window.location=\'/detail?type=section&did='+dept+'&cid='+course+'&sid='+section+'\'" >'+dept+' '+course+' '+section+'</p>';
			html += '<p class="block-location"  onclick="window.location=\'/detail?type=section&did='+dept+'&cid='+course+'&sid='+section+'\'" >'+building+' '+room+'</p></div>';
			//content.className = 'course';
			content.innerHTML = html;
		}
	}
}

function initSchedule(start, end){
	for(z = 1; z < 3; z++) {
	var schedule = document.getElementById('schedule-'+z);
	schedule.innerHTML = '';
	var dayheader = "<tr>";
	dayheader += "<td>&nbsp;</td>";
	dayheader += "<td class='dayheader'>Monday</td>";
	dayheader += "<td class='dayheader'>Tuesday</td>";
	dayheader += "<td class='dayheader'>Wednesday</td>";
	dayheader += "<td class='dayheader'>Thursday</td>";
	dayheader += "<td class='dayheader'>Friday</td>";
	dayheader += "</tr>"
	schedule.innerHTML += dayheader;
	for(i = start; i <= end; i++) {
		for(j = 0; j <= 3; j += 3) {
			var timeslot = "<tr id='"+i+":"+j+"0-"+z+"'>";
			timeslot += "<td id='"+i+"-header' class='time-header'>"+i+":"+j+"0</td>";
			timeslot += "<td id='Mon-"+i+":"+j+"0-"+z+"' class='worklist-cell'></td>";
			timeslot += "<td id='Tue-"+i+":"+j+"0-"+z+"' class='worklist-cell'></td>";
			timeslot += "<td id='Wed-"+i+":"+j+"0-"+z+"' class='worklist-cell'></td>";
			timeslot += "<td id='Thu-"+i+":"+j+"0-"+z+"' class='worklist-cell'></td>";
			timeslot += "<td id='Fri-"+i+":"+j+"0-"+z+"' class='worklist-cell'></td>";
			timeslot += "</tr>"
			schedule.innerHTML += timeslot;
		}
	}
	}
}

var remove_wlitem_req = getXmlHttpRequestObject();

function removeWorklistItem(dept,course,section) {
	var user = getCookie('user'); 
	if (user != null ){
		if (remove_wlitem_req.readyState == 4 || remove_wlitem_req.readyState == 0) {
			getStartEnd(user);
			remove_wlitem_req.open("GET", 'auth/ajax/worklist?action=remove&dept='+dept+'&course='+course+'&section='+section, true);
			remove_wlitem_req.onreadystatechange = handleRemoveWorklistItem;
			remove_wlitem_req.send(null);
		}
	}
}

function handleRemoveWorklistItem() {
	if (remove_wlitem_req.readyState == 4) {
		var xmlDoc = remove_wlitem_req.responseXML;
		var content = document.getElementById('worklist-error');
		var msg = xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;
		content.innerHTML = "<p class='notification-error-text'>"+msg+"</p>";
		var user = getCookie('user');
		getWorklistContent(user);
		getSummary(user);
		getWaypoints(user);
		$('#worklist-error').fadeIn(500).delay(3000).fadeOut(500);
		location.reload(true);
	}
}

var startend_req = getXmlHttpRequestObject();

function getStartEnd(email){
	var user = getCookie('user'); 
	if (user != null ){
		if (startend_req.readyState == 4 || startend_req.readyState == 0) {
			startend_req.open("GET", 'auth/ajax/summary?action=getstartend&email='+email, true);
			startend_req.onreadystatechange = handleStartEnd;
			startend_req.send(null);
		}
	}
}

function handleStartEnd() {
	if (startend_req.readyState == 4) {
		var xmlDoc = startend_req.responseXML;
		var content = document.getElementById('worklist-error');
		var start = parseInt(xmlDoc.getElementsByTagName("start")[0].childNodes[0].nodeValue.split(":")[0]);
		var end = parseInt(xmlDoc.getElementsByTagName("end")[0].childNodes[0].nodeValue.split(":")[0]);
		initSchedule(start,end);
	}
}

var summary_req = getXmlHttpRequestObject();

function getSummary(email){
	var user = getCookie('user'); 
	if (user != null ){
		if (summary_req.readyState == 4 || summary_req.readyState == 0) {
			summary_req.open("GET", 'auth/ajax/summary?action=getsummary&email='+email, true);
			summary_req.onreadystatechange = handleSummary;
			summary_req.send(null);
		}
	}
}

function handleSummary() {
	if (summary_req.readyState == 4) {
		var xmlDoc = summary_req.responseXML;
		var content = document.getElementById('summary');
		var summary = xmlDoc.getElementsByTagName("summary")[0].childNodes[0].nodeValue;
		content.innerHTML = summary;
	}
}

var waypoints_req = getXmlHttpRequestObject();


function getWaypoints(email,term){
	var user = getCookie('user'); 
	if (user != null ){
		if (waypoints_req.readyState == 4 || waypoints_req.readyState == 0) {
			waypoints_req.open("GET", 'auth/ajax/summary?action=getwaypoints&email='+email+'&term='+term, true);
			waypoints_req.onreadystatechange = handleWaypoints;
			waypoints_req.send(null);
		}
	}
}

var map;

function handleWaypoints() {
	if (waypoints_req.readyState == 4) {
		var xmlDoc = waypoints_req.responseXML;
		if( xmlDoc.getElementsByTagName("response")[0].hasChildNodes()) {
		var parent = xmlDoc.getElementsByTagName("response")[0].getElementsByTagName("waypoint");
		var waypoint = new Array();
		var origin;
		var destination;
			for (k = 0; k < parent.length; k++) {
				var lat = parent[k].getElementsByTagName("lat")[0].childNodes[0].nodeValue;
				var long = parent[k].getElementsByTagName("long")[0].childNodes[0].nodeValue;
				var latlng = new google.maps.LatLng(lat, long);
				if(k == 0){
					origin = latlng;
					initMap(origin);
					
				}
				else if (k == parent.length -1)
					destination = latlng;
				else {
					waypoint.push({
					      location: latlng,
					      stopover: true
					    });
				}
			}
		var marker = new google.maps.Marker({position: origin});
		marker.setMap(map);
		calcRoute(origin,waypoint,destination);
		}
	}
}

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();

function initMap(latlng) {
	if(latlng != null) {
	directionsDisplay = new google.maps.DirectionsRenderer();
//	var latlng = new google.maps.LatLng(lat, long);
	var myOptions = {
		zoom : 18,
		center : latlng,
		mapTypeId : google.maps.MapTypeId.HYBRID
	};

	map = new google.maps.Map(document.getElementById("map"), myOptions);
	directionsDisplay.setMap(map);
	}
	else {
		document.ElementById("map").innerHTML = "<p class='header'>No building information</p>"
	}
}

function calcRoute(start, waypoints, end) {
	  var request = {
	    origin:start,
	    waypoints : waypoints,
	    destination:end,
	    travelMode: google.maps.TravelMode.WALKING
	  };
	  directionsService.route(request, function(result, status) {
	    if (status == google.maps.DirectionsStatus.OK) {
	      directionsDisplay.setDirections(result);
	    }
	  });
}

